package lesson09;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @Date 2023-02-08
 */
public class Demo_1202_Semaphore {
    public static void main(String[] args) {
        // 创建信号量的对象, 并指定可用资源数量
        Semaphore semaphore = new Semaphore(5);

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "开始申请资源...");
                try {
                    // 申请资源
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "=====申请资源成功.");
                    // 持有一会
                    TimeUnit.SECONDS.sleep(1);
                    // 释放资源
                    semaphore.release();
                    System.out.println(Thread.currentThread().getName() + "释放资源.");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        // 创建多个线程去申请资源
        for (int i = 0; i < 20; i++) {
            Thread thread = new Thread(runnable);
            // 启动线程
            thread.start();
        }

    }
}
